package puc.redes.examples.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class TCPServer1 {
	ServerSocket serverSocket;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	TCPServer1() {
	}

	void run() {
		try {
			// 1. creamos el socket
			serverSocket = new ServerSocket(2512);
			
			// 2. esperamos a que alguien se conecte
			System.out.println("Esperando una conexion");
			connection = serverSocket.accept();
			System.out.println("Conexion recibida "
					+ connection.getInetAddress().getHostName());
			
			// 3. obtener los stream de entrada y salida
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			in = new ObjectInputStream(connection.getInputStream());
			sendMessage("Conexion exitosa");
			
			// 4. Las dos partes se comunican a través de los stream de datos
			do {
				try {
					message = (String) in.readObject();
					System.out.println("cliente: " + message);
					if (message.equals("chau"))
						sendMessage("chau!");
				} catch (ClassNotFoundException classnot) {
					System.err.println("Datos recibidos en formato desconocido");
				}
			} while (!message.equals("chau"));
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			// 4: cierre de la conexión
			try {
				in.close();
				out.close();
				serverSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("server: " + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(String args[]) {
		TCPServer1 server = new TCPServer1();
		while (true) {
			server.run();
		}
	}
}
